﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Medianamik.Core.ImportExport
{
    public class Medianamik2RecordAdapter : Record
    {
        private Medianamik.Core.Node _node;
        protected Medianamik.Core.Node Node
        {
            get
            {
                return _node;
            }
        }
        public Medianamik2RecordAdapter(Node node)
        {
            _node = node;
        }

       public override Guid NodeId
        {
            get
            {
                return Node.ID;
            }

        }

        public override Guid NodeTypeId
        {
            get
            {
                return Node.NodeTypeID;
            }

        }

        public override Guid? ParentNodeId
        {
            get
            {
                return Node.ParentID;
            }

        }

        public override short Position
        {
            get
            {
                return Node.Position;
            }
        }

        public override int Flags
        {
            get
            {
                return Node.Flags;
            }
        }

        public override DateTime CreatedOn { get { return Node.CreatedOn; } }

        public override List<RecordInstance> Instances
        {
            get
            {
                return Node.Instances.Select(i => (RecordInstance)new Medianamik2RecordInstanceAdapter(i)).ToList();  
            }
        }

        public override List<RecordProperty> Properties
        {
            get
            {
                return Node.Instances.SelectMany(i => i.Properties)
                    .Distinct(new NodePropertyEqualityComparer())
                    .Where(p=> p.IsOwnProperty)
                    .Select(p=> (RecordProperty)new Medianamik2RecordPropertyAdapter(p)).ToList() ;
            }
        }


        private class NodePropertyEqualityComparer : IEqualityComparer<NodeProperty>
        {
            #region IEqualityComparer<NodeProperty> Members

            public bool Equals(NodeProperty x, NodeProperty y)
            {
                return GetHashCode(x).Equals(GetHashCode(y));
            }

            public int GetHashCode(NodeProperty obj)
            {
                return obj.NodeTypePropertyID.GetHashCode() ^ obj.Culture.Name.ToLower().GetHashCode();  
            }

            #endregion
        }


    }
}
